package com.can.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean:3             @Qualifier值要与@Bean的name值相同
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /*
            anon：无需认证就可以访问
            authc: 必须认证了才能访问
            user: 必须拥有 记住我 功能才能用
            perms: 拥有对某个资源的权限才能访问;
            role: 拥有某个角色权限才能访问
         */

        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权    401就是未授权  正常情况下，没有授权会调转到未授权页面
        //LinkedHashMap perms 得在authc前面 才会生效  因为key:/user/** 会变成只需要认证就能访问 而不需要授权
        filterMap.put("/user/add","perms[user:add]"); //必须有user:add权限才能访问
        filterMap.put("/user/update","perms[user:update]"); //必须有user:update权限才能访问

        filterMap.put("/","anon");
//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
        filterMap.put("/user/**","authc");


        bean.setFilterChainDefinitionMap(filterMap);

        //设置拦截后 跳转到登录页面得请求
        bean.setLoginUrl("/toLogin");
        //设置未授权 跳转到的请求
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

    //DafaultWebSecurityManager:2
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);

        return securityManager;
    }

    //创建 realm 对象,需要自定义
    @Bean(name="userRealm") //默认name就是方法名:1
    public UserRealm userRealm(){
        return new UserRealm();
    }


    //整合ShiroDialect:用来整合Shiro和thymeleaf
    @Bean
    public ShiroDialect getShiroDiabect(){
        return new ShiroDialect();
    }
}
